<template>
  <div class="layout" @click.stop="aotuTab=false">
    <div class="header">
      <el-button type="primary" size="mini" @click="handleAdd">
        {{ $t('btn.save') }}
      </el-button>
    </div>
    <el-tabs v-model="essential">
      <el-tab-pane :label="$t('market.info')" name="information">
        <el-form ref="purchaseRef" :model="optionValue" label-width="100px" size="mini">
          <el-form-item :label="$t('market.billType')">
            <el-select v-model="optionValue.fbillType" filterable @change="queryProval">
              <el-option v-for="item in mostatusData" :key="item.fid" :label="item.fname" :value="item.fid" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.billNo')">
            <el-input v-model="optionValue.fbillNo" disabled />
          </el-form-item>
          <!--          <el-form-item label="库存组织">-->
          <!--            <el-select v-model.trim="optionValue.fstockorgid">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="货主">-->
          <!--            <el-select v-model.trim="optionValue.fownerid" disabled>-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item :label="$t('market.orderDate')">
            <el-date-picker
              v-model.trim="optionValue.fdate"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item :label="$t('market.stocker')">
            <el-autocomplete
              v-model.trim="optionValue.fstockerName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch3"
              @focus="querySalesperson(3)"
              @select="marketData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="marketVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fuserName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.deaprt')">
            <el-autocomplete
              v-model.trim="optionValue.fdeptName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch8"
              @focus="getBasicUnit('SX_V_WORKSHOP')"
              @select="selUnit"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="unitVisabled=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.note')" style="width: 50%;">
            <el-input v-model.trim="optionValue.fremark" style="width: 500px" />
          </el-form-item>
        </el-form>
        <div>
          <div style="margin-bottom: 5px">
            <el-button size="mini" @click="twoLine(1)">{{ $t('btn.newHang') }}<!--新增行--></el-button>
            <el-button size="mini" @click="twoLine(2)">{{ $t('btn.delHang') }}<!--删除行--></el-button>
            <el-button size="mini" @click.native="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
          </div>
          <jc-table
            :table-data="tableData"
            :table-header="tableHeader"
            :table-height="tableHeight"
            serial
            :get-summaries="getSummaries"
            show-summary
            @rowClick="rowClick"
            @cellClick="cellClick"
          >
            <!--  物料编码  -->
            <template v-slot:billSlot="col">
              <el-input
                v-model.trim="col.scope.row.fnumber"
                size="mini"
                @input="getAtuo(col.scope.$index, col.scope.row.fnumber)"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="handleGetMateriel(col.scope.row, col.scope.$index)"
                />
              </el-input>
              <div v-if="aotuTab && indexSelf === col.scope.$index" :class="indexSelf<7 ? 'tabPosit': 'tabPosit1'">
                <number-code :fnumber="fnumber" @material="materialData" />
              </div>
            </template>
            <!--  数量  -->
            <template v-slot:tagSlot="col">
              <el-input-number v-model="col.scope.row.fqty" size="mini" />
            </template>
            <!--  物料总价值  -->
            <template v-slot:btnState="col">
              <el-input-number v-model="col.scope.row.fworth" size="mini" />
            </template>
            <!-- 仓库 -->
            <template v-slot:operaSlot="col">
              <el-input
                v-model="col.scope.row.fstockName"
                size="mini"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="handleWarehouse(col.scope.$index)"
                />
              </el-input>
            </template>
            <template v-slot:text1Slot="col">
              <el-select v-model.trim="col.scope.row.fstockorgentryid" disabled>
                <el-option
                  v-for="option in teamList"
                  :key="option.fid"
                  :label="option.fname"
                  :value="option.fid"
                />
              </el-select>
            </template>
            <template v-slot:text2Slot="col">
              <el-select v-model.trim="col.scope.row.fownerentryid" disabled>
                <el-option
                  v-for="option in teamList"
                  :key="option.fid"
                  :label="option.fname"
                  :value="option.fid"
                />
              </el-select>
            </template>
            <!--库位-->
            <template v-slot:text3Slot="col">
              <el-select v-model="col.scope.row.fcodefnumber" size="mini" @change="handelCode(col.scope.$index)">
                <el-option v-for="item in col.scope.row.codes" :key="item.fid" :label="item.positionfnumber" :value="item.fnumber" />
              </el-select>
            </template>
            <!--  备注  -->
            <template v-slot:btnSlot="col">
              <el-input v-model.trim="col.scope.row.fremark" size="mini" />
            </template>
          </jc-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.fince')" name="first">
        <el-form :model="optionValue" label-width="100px" size="mini">
          <el-form-item :label="$t('market.settleCurr')" prop="fsettleCurrId"> <!--结算币别-->
            <el-autocomplete
              v-model.trim="optionValue.fsettleCurr"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch5"
              size="mini"
              @focus="queryTBdCurrency"
              @select="currencyData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="currencyVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.exchangeType')"><!--汇率类型-->
            <el-input v-model.trim="optionValue.fexchangeType" placeholder="请输入汇率类型" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.localCurr')"><!--本位币-->
            <el-input v-model.trim="optionValue.flocalCurr" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.exchangeRate')"><!--汇率-->
            <el-input v-model.trim="optionValue.fexchangeRate" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.worthall')"><!--总价zhi-->
            <el-input v-model.trim="optionValue.fworthall" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.worthalllc')"><!--总价值(本位币)-->
            <el-input v-model.trim="optionValue.fworthalllc" disabled size="mini" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <!--物料弹窗-->
    <material v-if="isMateria" @material="materialData" />
    <!--仓管员列表-->
    <market v-if="marketVisiblit" :staff-type="3" @market="marketData" />
    <!--  数据字典弹窗  -->
    <unit v-if="unitVisabled" :msg="funit" @unit="selUnit" />
    <!--结算币别列表-->
    <currency v-if="currencyVisiblit" @currency="currencyData" />
    <!--仓库-->
    <selectCK
      v-if="seleceVisiblit"
      :fmaterial-id="stockFnumber"
      :msg="2"
      @client="selectData"
    />
  </div>
</template>

<script>
import { insertStkOtherinstockDetails } from '@/api/repertory/picking/otherWarehousing'
import { queryFxxchange, queryRate, queryViewItem } from '@/api/marketManage/marketOrder'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import bility from '@/mixin/Operability'
import jumpMateriel from '@/components/JumpMateriel'
import { queryTBdCodeListByFnumber } from '@/api/repertory/picking/otherDelivery'

export default {
  name: 'OtherWarehousingAdd',
  components: {
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    unit: () => import('@/views/basic/createMateriel2/components/unit'),
    market: () => import('@/views/market/marketManage/createMarkerOrder/components/market'),
    material: () => import('@/views/market/marketManage/createMarkerOrder/components/material'),
    numberCode: () => import('@/components/NumberCode'),
    selectCK: () => import('@/views/production/collect/components/seleceCK')
  },
  mixins: [jumpMateriel, autocomplete, bility],
  data() {
    return {
      essential: 'information',
      seleceVisiblit: false, // 仓库
      marketVisiblit: false, // 仓管
      unitVisabled: false, // 部门
      currencyVisiblit: false, // 币别
      funit: 'SX_V_WORKSHOP',
      stockFnumber: '',
      fnumber: '',
      isMateria: false,
      aotuTab: false,
      // 表头数据
      tableData: [
        {
          codes: [],
          fnumber: '',
          fmodel: '',
          fspecificaTion: '',
          fdescripTion: '',
          funitName: '',
          fqty: 0,
          fworth: 0,
          fstockName: '',
          stockQty: '',
          fownerentryid: 1,
          fstockorgentryid: 1,
          fownerid: 1
        }
      ],
      tableHeader: [
        { label: this.$t('market.fmaterial'), type: 'bill', prop: 'fnumber', width: '150px' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200px' },
        { label: this.$t('market.funit'), prop: 'funitName', width: '80' },
        { label: this.$t('market.fqty'), type: 'tag', prop: 'fqty', width: '80' },
        { label: this.$t('market.globalValue'), type: 'state', prop: 'fworth', width: '80' },
        { label: this.$t('market.stock2'), type: 'operate', prop: 'fstockName' },
        { label: this.$t('market.stockQty'), prop: 'stockQty' },
        { label: this.$t('market.storageLoca'), type: 'text3', prop: 'fcodefnumber', width: '100' },
        { label: this.$t('market.storageQty'), prop: 'fcodeQty', width: '80' },
        // { label: '入库组织', type: 'text1', prop: 'fstockorgentry' },
        // { label: '货主', type: 'text2', prop: 'fownerentryid' },
        { label: this.$t('market.note'), type: 'btn', prop: 'fremark' }
      ],
      optionValue: {
        fbillType: 213,
        fstockerId: '',
        fstockerName: '',
        fremark: '',
        fstockorgid: 1,
        fownerid: 1,
        fdate: new Date().toLocaleDateString().replaceAll('/', '-')
      },
      tableHeight: '',
      indexSelf: 0, // 表格index
      mostatusData: [] // 单据类型
    }
  },
  watch: {
    // 监听库存组织变化
    'optionValue.fstockorgid': {
      handler(val) {
        this.optionValue.fownerid = val
        this.tableData.map(res => {
          res.fstockorgentryid = val
          res.fownerentryid = val
        })
      }
    }
  },
  created() {
    // 单据类型
    this.business()
    this.queryProval()
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 280px)' : '400px'
  },
  methods: {
    // 监听单据类型
    queryProval() {
      const DATA = {
        fid: this.optionValue.fbillType || 0,
        viewName: 'SX_STK_OTHERINSTOCKBILLTYPE'
      }
      queryFxxchange(DATA).then(res => {
        if (res.code === 0) {
          this.optionValue = {
            ...this.optionValue,
            fstockorgid: res.data.fsaleorgid,
            ...res.data
          }
        }
      })
    },
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.indexSelf = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber = fnumber
      }, 600)
    },
    // 新增数据
    handleAdd() {
      this.details = []
      const data = {
        ...this.optionValue,
        details: this.tableData
      }
      insertStkOtherinstockDetails(data).then(res => {
        const { code, message } = res
        if (code !== 0) {
          this.$confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.tableData = []
        this.production = {
          fbillType: 213,
          fstockerId: '',
          fstockerName: '',
          fremark: '',
          fdate: new Date().toLocaleDateString().replaceAll('/', '-')
        }
        // 关闭当前页面
        this.$store.dispatch('tagsView/guanbi', this.$route)
        this.$router.push({ path: `/otherWarehousingDetails/${res.data.fid}` })
        this.$message({ showClose: true, message: res.message, type: 'success' })
      })
    },
    // 打开物料弹窗
    handleGetMateriel(row, index) {
      this.isMateria = true
      this.indexSelf = index
    },
    // 物料数据
    materialData(item) {
      if (item.fmaterialId) {
        const items = this.tableData[this.indexSelf]
        items.fmaterialId = item.fmaterialId
        items.fnumber = item.fnumber
        items.fname = item.fname
        items.fdescripTion = item.fdescripTion
        items.fspecificaTion = item.fspecificaTion
        items.funitId = item.funitId
        items.funitName = item.funit
        items.fmodel = item.fmodel
        items.fstockId = item.fstockId
        items.fstockName = item.fstock
        items.fworth = item.faverageprice
        this.queryTBdCodeList(items, items.fnumber)
      }
      this.isMateria = item.isMaterialDialog
    },
    // 根据物料查询库位
    queryTBdCodeList(items, fnumber) {
      queryTBdCodeListByFnumber({ fnumber }).then(res => {
        if (res.code === 0) {
          items.codes = res.data
          // items.fcodefnumber = res.data.fnumber
        }
      })
    },
    // 获取结算币别数据(子传父)
    currencyData(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.optionValue.fsettleCurr = item.fsettleCurrIdName || item.fname
        this.optionValue.fsettleCurrId = item.fsettleCurrId || item.fcurrencyId
        this.optionValue.flocalCurrId && this.querySalerRate()
      }
      this.currencyVisiblit = false
    },
    // 查询销售订单汇率
    async querySalerRate() {
      const DATA = {
        tocurrId: this.optionValue.flocalCurrId, // 本位币
        fromcurrId: this.optionValue.fsettleCurrId, // 结算币别
        queryDate: this.optionValue.fdate
      }
      const { data: RES, code, message } = await queryRate(DATA)
      if (code === 0) {
        this.optionValue.fexchangeRate = RES.exchangeRate
        this.optionValue.fexchangeType = RES.exchangeTypeName
        this.optionValue.fexchangeTypeId = RES.exchangeTypeId
      } else {
        this.optionValue.fexchangeRate = ''
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 获取仓管员数据(子传父)
    marketData(item) {
      if (item.fuserId) {
        this.optionValue.fstockerName = item.fuserName
        this.optionValue.fstockerId = item.fuserId
      }
      this.marketVisiblit = false
    },
    // 数据字典选中
    selUnit(ev) {
      if (ev.fid) { // 生产部门
        this.optionValue.fdeptId = ev.fid
        this.optionValue.fdeptName = ev.fname
      }
      this.unitVisabled = false
    },
    // 打开仓库弹窗
    handleWarehouse(index) {
      const item = this.tableData[index].fnumber
      this.stockFnumber = item
      this.indexSelf = index
      this.seleceVisiblit = true
    },
    // 获取仓库数据
    selectData(ev) {
      if (ev.fstockId) {
        const item = this.tableData[this.indexSelf]
        item.fstockId = ev.fstockId
        item.fstockName = ev.fname
        item.stockQty = ev.sumQty
        this.queryTBdCodeList(item, item.fnumber)
      }
      this.seleceVisiblit = false
    },
    // 单据类型
    business() {
      queryViewItem({ viewName: 'SX_STK_OTHERINSTOCKBILLTYPE' }).then(res => {
        this.mostatusData = res.data.list
      })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增 删除行
    twoLine(ev) {
      const data = {
        codes: [],
        fnumber: '',
        fmodel: '',
        fspecificaTion: '',
        fdescripTion: '',
        funitName: '',
        fqty: 0,
        fworth: 0,
        fstockName: '',
        stockQty: '',
        fremark: '',
        fstockorgentryid: this.optionValue.fstockorgid,
        fownerentryid: this.optionValue.fstockorgid
      }
      if (ev === 1) {
        this.tableData.push(data)
      } else {
        this.tableData.splice(this.indexSelf, 1)
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.tableData[this.subscript][this.property]
      const ckid = this.tableData[this.subscript].fstockId
      const sumQty = this.tableData[this.subscript].stockQty
      this.tableData.map((res, index) => {
        if (index >= this.subscript) {
          if (this.property === 'fstockName') {
            res.fstockId = ckid
            res.stockQty = sumQty
          }
          res[this.property] = item
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.layout {
  @include listBom;
  padding: 10px;
  background: #FFFFFF;
  .el-tabs {
    &::v-deep .el-tabs__content {
        min-height: 80vh;
    }
  }
  .tabPosit {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: 3.5vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 99999!important;
  }
  .tabPosit1 {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: -25.69vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      //height: 35px;
      width: 275px;
      margin-bottom: 5px;
      .btnType{
        margin-right: 20px;
      }
      .el-date-editor.el-input{
        width: 100% !important;
      }
      .el-select{
        width: 100%;
      }
    }
  }
}
</style>
